package com.nrg.richie.server;

import java.io.OutputStream;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.nrg.richie.server.utils.StringUtils;

@SuppressWarnings("serial")
public class DownloadServlet extends HttpServlet{
	
	Logger logger = Logger.getLogger(DownloadServlet.class.getName());
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException {

	    String xml = (String) request.getSession().getAttribute(UploadServlet.XML_DOCUMENT_FILTERED);
	    
	    if (xml == null || xml.trim().length() == 0)
	        throw new ServletException("Invalid Session");
	    
	    try {
		    OutputStream out = response.getOutputStream();

		    byte[] bytes = xml.getBytes("UTF-8");
		    
		    response.setCharacterEncoding("UTF-8");
		    response.setContentType("application/xml; charset=utf-8");
		    response.setContentLength( bytes.length );
		    response.setHeader( "Content-Disposition", "attachment; filename=\"valogatott_hirdetesek.xml\"" );
		    
		    out.write(bytes);
		    
		    out.flush();
		    out.close();
	    } catch (Exception e) {
	    	logger.severe(StringUtils.getStacktraceAsString(e));
	    }
	}
	
}